import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';

import '../core/network/request.dart';
import '../core/store/user_store.dart';
import '../core/utils/global_context.dart';
import '../core/utils/toast.dart';
import '../model/login_model.dart';
import '../pages/main_page.dart';

class LoginViewModel extends ChangeNotifier {
  static const String _keyLogin = 'login_data';

  LoginModel? _loginModel;

  /// 获取当前登录数据
  LoginModel? get loginModel => _loginModel;

  /// 是否已登录
  bool get isLoggedIn => _loginModel?.token?.isNotEmpty == true;

  /// 加载本地缓存的登录数据
  Future<void> loadLogin() async {
    final jsonStr = Store().getString(_keyLogin);
    if (jsonStr.isNotEmpty) {
      try {
        _loginModel = LoginModel.fromJson(json.decode(jsonStr));
      } catch (e) {
        _loginModel = null;
      }
    }
    notifyListeners();
  }

  /// 保存登录数据到本地
  Future<void> saveLogin(LoginModel model) async {
    _loginModel = model;
    await Store().setString(_keyLogin, json.encode(model.toJson()));
    notifyListeners();
  }

  /// 清除登录信息
  Future<void> logout() async {
    _loginModel = null;
    await Store().remove(_keyLogin);
    notifyListeners();
  }

  Future<void> register(
      {required String username,
      required String password,
      required String avatar}) async {
    if (username.isEmpty || password.isEmpty) {
      toast('用户名和密码不能为空');
      return;
    }
    final passwordReg = RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$');
    if (!passwordReg.hasMatch(password)) {
      toast('密码必须至少6位，且包含字母和数字');
      return;
    }
    final request = RequestService();
    final res = await request.post('/user/register',
        data: {"username": username, "password": password, "avatar": avatar});
    toast(res.message ?? '操作成功');
  }

  Future<void> login({
    required String username,
    required String password,
  }) async {
    if (username.isEmpty || password.isEmpty) {
      toast('用户名和密码不能为空');
      return;
    }
    final passwordReg = RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$');
    if (!passwordReg.hasMatch(password)) {
      toast('密码必须至少6位，且包含字母和数字');
      return;
    }
    final request = RequestService();
    final res = await request.post('/user/login',
        data: {"username": username, "password": password});
    final String token = res.data.token;
    final String imId = res.data.im_id;
    final String avatar = res.data.avatar;
    _loginModel = LoginModel(username: username, avatar: avatar, token: token, imId: imId);
    saveLogin(_loginModel!);
    Navigator.pushReplacement(
      globalContext!,
      MaterialPageRoute(builder: (context) => const MainPage()),
    );
    toast(res.message ?? '操作成功');
  }

  Future<String> upload(File imageFile) async {
    final request = RequestService();
    final res = await request.uploadFile('/upload/file', fieldName: 'file', filePath: imageFile.path);
    return res.data.url;
  }
}
